package us.mooresr.geartrack.server.handler;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import us.mooresr.geartrack.server.DAO;
import us.mooresr.geartrack.shared.action.GetAllAvailableItemsAction;
import us.mooresr.geartrack.shared.action.GetAllAvailableItemsResult;
import us.mooresr.geartrack.shared.action.GetAllCheckedOutItemsResult;
import us.mooresr.geartrack.shared.model.Item;
import us.mooresr.geartrack.shared.model.Loan;
import us.mooresr.geartrack.shared.model.LoanDTO;
import us.mooresr.geartrack.shared.model.Person;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.gwtplatform.dispatch.server.ExecutionContext;
import com.gwtplatform.dispatch.server.actionhandler.ActionHandler;
import com.gwtplatform.dispatch.shared.ActionException;

public class GetAllAvailableItemsActionHandler 
	implements ActionHandler<GetAllAvailableItemsAction, GetAllAvailableItemsResult> {

	@Override
	public GetAllAvailableItemsResult execute(GetAllAvailableItemsAction arg0,
			ExecutionContext arg1) throws ActionException {
		DAO dao = new DAO();
		
		Objectify ofy = dao.ofy();
		
		List<Item> itemList =  ofy.query(Item.class).list();
		List<Loan> loanList = ofy.query(Loan.class).filter("checkInDate", null).list();
		
		HashSet<Long> itemSet = new HashSet<Long>();
		for (Item i : itemList) {
			itemSet.add(i.getId());
		}
		
		HashSet<Long> loanSet = new HashSet<Long>();
		for (Loan l : loanList) {
			loanSet.add(l.getItemId());
		}
		
		itemSet.removeAll(loanSet);
		
		Map<Long, Item> itemMap = dao.ofy().get(Item.class, itemSet);
		
		ArrayList<Item> result = new ArrayList(itemMap.values());
		
		return new GetAllAvailableItemsResult(result);
	}

	@Override
	public Class<GetAllAvailableItemsAction> getActionType() {
		return GetAllAvailableItemsAction.class;
	}

	@Override
	public void undo(GetAllAvailableItemsAction arg0,
			GetAllAvailableItemsResult arg1, ExecutionContext arg2)
			throws ActionException {
		// TODO Auto-generated method stub
		
	}

}
